const { Sequelize, DataTypes, Op } = require("sequelize");
const { isRequiredParams, doSqlMiddle } = require("../utils/tool");
const { sqlLog } = require("../utils/logger");
const path = require("path");

const sequelize = new Sequelize({
  dialect: "sqlite",
  storage: path.join(__dirname, "../storage/users.sqlite"),
  logging: (msg) => {
    // 只记录第一个参数
    sqlLog.info(msg);
  },
});

/**
 * # 用户表的定义
 */
const User = sequelize.define("User", {
  id: {
    type: DataTypes.UUID,
    defaultValue: Sequelize.UUIDV1,
    unique: true,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
    defaultValue: "默认用户名",
  },
  phone: {
    type: DataTypes.STRING,
  },
  ps: {
    // 密码
    type: DataTypes.STRING,
    defaultValue: "123456",
  },
  station: {
    // 岗位信息 根据前端实际需求对应即可
    type: DataTypes.NUMBER,
    defaultValue: 0,
  },
  projectCount: {
    // 工程数量
    type: DataTypes.NUMBER,
    defaultValue: 0,
  },
  projectIncome: {
    // 项目总收入
    type: DataTypes.NUMBER,
    defaultValue: 0,
  },
});

async function createUser(data) {
  return doSqlMiddle(async () => {
    let user = await User.create(data);
    return user.toJSON();
  });
}

async function initSuperUser() {
  const users = await findUser();
  if (users.length === 0) {
    console.log("当前无用户，创建超级管理员...");
    createUser({
      name: "超级管理员",
      phone: "13540216307",
      station: 999,
      workArea: [
        {
          name: "我吃西红柿",
        },
      ],
    }).then(() => {
      console.log("超级管理员创建成功，账号：root 密码：123456");
    });
  }
}

async function findUser({ limit, page, id, name, phone, us, station } = {}, needPs = false) {
  const query = {
    attributes: { exclude: ["ps"] }, // 排除密码
    where: {},
  };
  if (needPs) {
    delete query.attributes;
  }
  if (limit) {
    query.limit = limit;
  }
  if (page) {
    query.offset = page * limit;
  }
  if (name) {
    query.where.name = {
      [Op.like]: `%${name}%`, // 模糊匹配姓名
    };
  }
  if (phone) {
    query.where.phone = phone;
  }
  if (id) {
    query.where.id = id;
  }
  if (us) {
    query.where.us = us;
  }
  if (station) {
    query.where.station = station;
  }

  if (Object.keys(query.where).length <= 0) {
    delete query.where;
  }

  return doSqlMiddle(async () => {
    let users = await User.findAll(query);
    return users.map((item) => item.dataValues);
  });
}

const canUpdateField = {
  name: true,
  phone: true,
  station: true,
  chargeTimes: true,
  permission: true,
};
async function updateUser(data) {
  let newData = {};
  for (let key in data) {
    if (canUpdateField[key]) {
      newData[key] = data[key];
    }
  }
  return doSqlMiddle(async () => {
    await User.update(newData, {
      where: {
        id: data.id,
      },
      returning: true,
    });
    const user = await findUser({ id: data.id });
    return user.length > 0 ? user[0] : {};
  });
}

module.exports = {
  User,
  createUser,
  findUser,
  initSuperUser,
  updateUser,
  sequelize,
};
